package cn.itsource.user.controller;

import cn.itsource.basic.exception.BusinessException;
import cn.itsource.user.service.IUserService;
import cn.itsource.user.domain.User;
import cn.itsource.user.query.UserQuery;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import java.util.List;
import java.util.Map;

/**
* 后端接口类；
*/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    public IUserService userService;

    /**
     * 接口：添加或修改
     * @param user  传递的实体
     * @return AjaxResult 响应给前端
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user){ 
        if( user.getId()!=null){
		userService.update(user);
        }else{
                userService.add(user);
	}
        return new AjaxResult();
       
    }

    /**
    * 接口：删除
    * @param id
    * @return AjaxResult 响应给前端
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult del(@PathVariable("id") Long id){
        userService.del(id);
        return new AjaxResult();
    }

    /**
    * 接口：批量删除
    * @param ids
    * @return AjaxResult 响应给前端
    */
    @PatchMapping
    public AjaxResult patchDel(@RequestBody Long[] ids){
        userService.patchDel(ids);
        return new AjaxResult();
    }

    /**
    * 接口：查询单个对象
    * @param id
    */
    @GetMapping("/{id}")
    public User findOne(@PathVariable("id")Long id) {
        return userService.findOne(id);
    }


    /**
    * 接口：查询所有
    * @return
    */
    @GetMapping
    public List<User> findAll(){
        return userService.findAll();
    }


   /**
    * 接口：分页查询或高级查询
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping
    public PageList<User> queryPage(@RequestBody UserQuery query) {
        return userService.queryPage(query);
    }

    /** 手机号注册 */
    @PostMapping("/register/phone")
    public AjaxResult phoneRegister(@RequestBody Map<String,String> map) {
        return userService.phoneRegister(map);
    }

    /** 邮箱注册 */
    @PostMapping("/register/email")
    public AjaxResult emailRegister(@RequestBody Map<String,String> map) throws MessagingException {
        return userService.emailRegister(map);
    }

    /** 邮箱注册：激活账号 */
    @GetMapping("/register/{id}")
    private String active(@PathVariable("id") Long id){
        try {
            userService.active(id);
            return "激活成功！";
        } catch (BusinessException e) {
            e.printStackTrace();
            return "激活失败！";
        }
    }
}
